package middleware

import (
	"net/http"

	"ginx/internal/global/configs"

	"github.com/gin-gonic/gin"
)

// 按照配置处理跨域请求
func Cors() gin.HandlerFunc {
	// 放行全部
	if configs.C.Cors.AllowAll {
		return cors_allow_all()
	}
	return cors_by_rules()
}

func cors_by_rules() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取请求的 Origin 头。若没有 Origin 头，就认为是同源请求。
		allow_origins := checkCors(c.GetHeader("Origin"))
		// 通过检查, 添加请求头
		if allow_origins != "" {
			c.Header("Access-Control-Allow-Origin", allow_origins)
			c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token,X-Token,X-User-Id")
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS,DELETE,PUT")
			c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type, New-Token, New-Expires-At")
			c.Header("Access-Control-Allow-Credentials", "true")
		}

		// 严格白名单模式且未通过检查，直接拒绝处理请求
		if allow_origins == "" && !configs.C.Cors.AllowAll && !(c.Request.Method == "GET" && c.Request.URL.Path == "/health") {
			c.AbortWithStatus(http.StatusForbidden)
		} else {
			// 非严格白名单模式，无论是否通过检查均放行所有 OPTIONS 方法
			if c.Request.Method == http.MethodOptions {
				c.AbortWithStatus(http.StatusNoContent)
			}
		}

		// 处理请求
		c.Next()
	}
}

func checkCors(currentOrigin string) string {
	for _, allow_origins := range configs.C.Cors.AllowOrigins {
		// 遍历配置中的跨域头，寻找匹配项
		if currentOrigin == allow_origins {
			return allow_origins
		}
	}
	return ""
}

// cors 全部放行
func cors_allow_all() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin")
		c.Header("Access-Control-Allow-Origin", origin)
		c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token,X-Token,X-User-Id")
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS,DELETE,PUT")
		c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type, New-Token, New-Expires-At")
		c.Header("Access-Control-Allow-Credentials", "true")

		// 放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		// 处理请求
		c.Next()
	}
}
